<?

/**
 *	json object frontend module
 *	this module parses any given json object to a html single file
 *
 *	goal of this module is to read api's
 */

class ObjectJson extends modTEXT {

	
	/**
	 *	constructor
	 * 	@param		array
	 */
	function __construct( $vars ) {

		$this->_addvars( $vars );
		$this->_ref();
	}
	
	
	/**
	 *	define route and add global functions
	 */
	public function output() {
		
		$this->addclass( $this->action );
		
		if( $this->action )
			$result = $this->{ "filter_" . $this->action }();

		if( $result )
			$result = "<ul>" . implode( "\n", $result ) . "</ul>";
			
		return $this->parse( $result ) . $this->render_js();
		
	}
	
	
	/**
	 *	basic parsers
	 *	defined by url, key and subkeys lists are created
	 */
	public function filter_basic() {
		
		// fetch content
		$content	= json_decode( @file_get_contents( $this->vars->url ));
		
		// fetch content by key
		$objects	= (array) $content->{ $this->vars->key };
		
		// parse list
		foreach( $objects as $object ) {
			$return[] = '<li class="json">';
			foreach((array) $this->vars->subkeys as $subkey ) {
				$return[] = '<span class="' . $subkey . '">' . $object->{ $subkey } . '</span>';
			}
			$return[] = '</li>';
		}
		
		return $return;
	
	}
	
	
	/**
	 *	json output
	 * 	defined by type, condt, key and subkeys
	 */
	public function api_output() {
		global $DB;
		
		$json = array();
		$objects = $DB->filter_objects( $this->vars->type, $this->vars->condt );
		if( stristr( $this->vars->type, 'cal' )) {
			$CAL = new CALENDAR( "Y-m-d H:i:s" );
			$objects = $CAL->filter_nodes_by_condt( $this->vars->type, $this->vars->condt );
		}
		
		if( $objects ) {
			
			$i = 0;
			foreach( $objects as $Object ) {
				foreach( $this->vars->subkeys as $subkey ) {
					$json[ $i ][ $subkey ] = $Object->get( $subkey );
				}
				$i++;
			}
			
		} 
		
		echo json_encode( array( $this->vars->key => $json ));
	}
		
} 



?>